package com.iamteer.day22;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/**
主要回顾：Properties
	1. 如果配置文件使用了中文，则需要使用字符流解决，否则会出现乱码（因为字节流默认使用 ISO8859-1 编码）
	2. 如果修改了 Properties 文件的内容，需要重新生成 Properties 文件
 */
public class Properties_eg {

	public static void main(String[] args) throws IOException {
//		createProperties();
//		readProperties();
//		updateProperties();
		testOpenCount();
	}

	public static void updateProperties() throws IOException {
		Properties properties = new Properties();
		properties.load(new FileReader("user.properties"));
		properties.setProperty("Celia", "000");
		properties.store(new FileWriter("user.properties"), "update password");
	}
	
	//读取配置文件信息
	public static void readProperties() throws IOException {
		 Properties properties = new Properties();
		 properties.load(new FileReader("user.properties"));
		 Set<Entry<Object, Object>> entries = properties.entrySet();
		 for (Entry<Object, Object> entry : entries) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}
	}
	
	//创建配置文件信息
	public static void createProperties() throws IOException {
		Properties properties = new Properties();
		properties.setProperty("Chuck", "123");
		properties.setProperty("Celia", "456");
		properties.setProperty("Megan", "789");
		properties.setProperty("狗娃", "032");
		properties.setProperty("狗剩", "349");
//		properties.put(key, value);	//不建议使用，因为 put 方法要求低，可以传任意类型，可能会导致运行时转换出错
		
		//遍历 Properties
		Set<Entry<Object, Object>> entries = properties.entrySet();
		for (Entry<Object, Object> entry : entries) {
			System.out.println(entry.getKey() + "\t" +entry.getValue());
		}
		
		//配置文件持久化
//		properties.store(new FileOutputStream("user.properties"), "user&password");	//会使用拉丁码表
		properties.store(new FileWriter("user.properties"), "user&password");	//使用机器环境码表
	}
	
	public static void testOpenCount() throws IOException {
		File file = new File("count.properties");
		if (! file.exists()) {
			file.createNewFile();
		}
		
		Properties properties = new Properties();
		properties.load(new FileReader(file));
		int count = 0;
		String value = properties.getProperty("count");
		if(value != null){
			count = Integer.parseInt(value);
		}
		
		if (count >= 3) {
			System.out.println("试用完毕，请购买正版软件！");
			System.exit(0);
		}
		
		count++;
		System.out.println("你已经使用本软件 " + count + " 次");
		properties.setProperty("count", count+"");
		properties.store(new FileOutputStream(file), "runtime");
	}
	
}
